package demo;

import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class SomeServiceImpl implements SomeService{
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	
	private Log logger = LogFactory.getLog(getClass());

	@Override
	@Cacheable(value = "cacheTest", key = "#id")
	public User findUser(Long id) {
		
		System.out.println("get from Db");
		
		String sql = "select * from user where id = ?";
		Object[] obj = {id};
		User user = jdbcTemplate.queryForObject(sql, obj, new BeanPropertyRowMapper<>(User.class));
		return user;
	}
	
	
	@CacheEvict(value="cacheTest",key="#user.getId()")
	@Override
	public int update(User user){
		String sql = "update user set name=?, phone=? where id = ?";
		return jdbcTemplate.update(sql, new Object[]{user.getName(),user.getPhone(),user.getId()});
	}

	
	
	@Override
	@Cacheable(value = "cacheList")
	public Collection<User> findAllUsers() {
		
		logger.info("get user list from DB ...");
		
		String sql = "select * from user";
		List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
		return userList;
	}

	@Override
	@CacheEvict(value = "cacheList", allEntries=true)
	public void addUser(User user) {
		
		logger.info("add user ...");
//		jdbcTemplate.update("insert into user (name, phone) values (?,?) ", new Object[]{"xiaoli", "1234"});
		jdbcTemplate.update("insert into user (name, phone) values (?,?) ", new Object[]{user.getName(),user.getPhone()});
		
	}

}
